<?php
namespace common\components\logistics;

use yii;
use yii\base\Component;

/**
 * Created by PhpStorm.
 * User: 140265
 * Date: 2016/11/21
 * Time: 15:55
 */
abstract class Request extends Component
{
    /**
     * 基础url
     *
     * @var string
     */
    protected $base_url = '';

    /**
     * 超时时间
     *
     *  @var int
     */
    protected $timeout = 1;

    /**
     * 接口要传递的公共参数
     * @var array
     */
    protected $query_param = array();

    public function init()
    {
        parent::init();
    }

    /**
     *  POST请求
     *
     * @param $url
     * @param array $data
     * @return array
     */
    public function post($url, $data = [])
    {
        $url = $this->_fetchUrl($url);
        $result = Yii::$app->httpclient->post($url, $data);
        return $this->_process($result, $url, $data);
    }

    /**
     * GET请求
     *
     * @param string $url
     * @param array $data
     * @return array
     */
    public function get($url = '', $data = [])
    {
        $data && $url .= '?' . http_build_query($data);
        $url = $this->_fetchUrl($url);
        $result = Yii::$app->httpclient->get($url);
        return $this->_process($result, $url, $data);
    }


    protected function _fetchUrl($url)
    {
        echo '<pre>';
        var_dump($this->base_url);
        exit;
        $url = rtrim($this->base_url, '/' ) . '/'. ltrim($url, '/');
        $url .= array_key_exists('query', parse_url($url)) ? '&' : '?';
        $url .= http_build_query($this->query_param);
        return $url;
    }

    /**
     * 处理请求
     *
     * @param string $result 接口返回值
     * @param string $url 请求接口URL
     * @param mixed $data 提交参数
     *
     * @return array
     */
    abstract protected function _process($result, $url, $data = array());
}